/**
 * 复制粘贴
 */

import ClipboardJS from 'clipboard'
import { Toast } from 'vant'

export const handleCopy = (text: string, cb = (e?: boolean) => {}, hideToast = false) => {
  const elBtn = document.createElement('button')
  const clipboard = new ClipboardJS(elBtn)
  elBtn.setAttribute('data-clipboard-action', 'copy')
  elBtn.setAttribute('data-clipboard-text', text)
  clipboard.on('success', function(e) {
    if (!hideToast) {
      Toast('复制成功')
    }
    e.clearSelection()
    cb(true)
  })
  clipboard.on('error', function(e) {
    if (!hideToast) {
      Toast('请长按复制')
    }
    e.clearSelection()
    cb(false)
  })
  elBtn.dispatchEvent(new Event('click'))
}
